package com.web.orderservice.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.web.orderservice.client.ProductServiceFeignClient;
import com.web.orderservice.entity.Order;
import com.web.orderservice.entity.PageVO;
import com.web.orderservice.entity.Product;
import com.web.orderservice.service.OrderService;
import jakarta.annotation.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
public class OrderController {

    @Resource
    private OrderService orderService;

    @Resource
    private ProductServiceFeignClient productServiceFeignClient;


    @RequestMapping("/order/{id}")
    public ResponseEntity<Order> findProductById(@PathVariable Integer id){
        Order order = orderService.getById(id);
        //使用feign客户端调用商品服务
        ResponseEntity<Product> entity = productServiceFeignClient.findProductById(order.getProductId());
        order.setProduct(entity.getBody());
        return ResponseEntity.ok(order);
    }

    @GetMapping("/orders")
    public ResponseEntity<List<Order>> findAllProducts(){
        List<Order> list = orderService.list();
        return ResponseEntity.ok(list);
    }


    @GetMapping("/orders-page")
    public ResponseEntity<PageVO> findOrdersPage(
            @RequestParam(value = "current",required = false,defaultValue = "1") Integer current,
            @RequestParam(value = "pageSize",required = false,defaultValue = "10") Integer pageSize){
        Page<Order> page = orderService.page(new Page<>(current, pageSize));
        PageVO pageVO = new PageVO(current,pageSize,page.getTotal(),page.getRecords());
        return ResponseEntity.ok(pageVO);
    }


    @PostMapping("/order")
    public ResponseEntity<String> addOrder(@RequestBody Order order){
        orderService.save(order);
        return ResponseEntity.ok("OK");
    }


    @PutMapping("/order")
    public ResponseEntity<String> updateOrder(@RequestBody Order order){
        orderService.updateById(order);
        return ResponseEntity.ok("OK");
    }


    @DeleteMapping("/order/{id}")
    public ResponseEntity<String> deleteOrder(@PathVariable Integer id){
        orderService.removeById(id);
        return ResponseEntity.ok("OK");
    }


}
